package com.hangzhou.xyj.ui.fragment;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.RecordDao;
import com.hangzhou.xyj.event.AnimationEvent;
import com.hangzhou.xyj.model.RecordModel;
import com.hangzhou.xyj.model.type.EPlayControlType;
import com.hangzhou.xyj.ui.adapter.MyRecordAdapter;
import com.hangzhou.xyj.ui.fragment.base.BaseFragment;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.constants.AppConstants;
import com.mediaideas.videoengine.IMediaPlaybackService;
import com.mediaideas.videoengine.IMediaPlaybackStatusCallback;
import com.mediaideas.videoengine.utils.FileUtils;
import com.mediaideas.videoengine.utils.MusicUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页唱戏 ->我的录音
 *
 * @author neo.duan
 */
public class MyRecordFragment extends BaseFragment implements OnClickListener, MyRecordAdapter.OnPlayBackListener, MyRecordAdapter.OnItemClickListener {

    protected final static int MSG_REFRESH_PROGRESS_POS = 0X0002;//刷新进度
    protected MusicUtils.ServiceToken mToken;
    protected IMediaPlaybackService mService = null;
    protected Handler mHandler;
    // 播放器Service的链接回调
    protected ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            try {
                mService = IMediaPlaybackService.Stub.asInterface(iBinder);
                mService.setMediaPlaybackStatusCallback(mMediaPlaybackStatusCallback);
//                mOnServiceConnectedListener.onServiceConnected();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mService = null;
        }
    };
    private RecyclerView mRecyclerView;
    private MyRecordAdapter mAdapter;
    //    private String mCurrentPlayFilePath;//当前播放的文件的path
    private long mDuration;//时长
    private MyTextView mTvCurrentTime;//当前播放时间
    private MyTextView mTvTotalTime;//总的播放时间
    private SeekBar mSeekBar;//进度条
    private ImageView mPlayStatus;//设置播放按钮
    private boolean isPause = true;//是否暂停
    private boolean isStop = true;//是否播放结束
    // 媒体播放器回调AIDL接口
    protected IMediaPlaybackStatusCallback mMediaPlaybackStatusCallback = new IMediaPlaybackStatusCallback.Stub() {
        @Override
        public void onMediaPlayBuffering(int percent) throws RemoteException {

        }

        /**
         * 播放完成
         * @throws RemoteException
         */
        @Override
        public void onMediaPlayerCompletion() throws RemoteException {
            isPause = true;
            isStop = true;
            mAdapter.setPlayStatus(mPlayStatus, MyRecordAdapter.PlayStatus.PAUSE);
        }

        @Override
        public void onMediaPlayerError(int what, int extra) throws RemoteException {

        }

        @Override
        public void onMediaPlayerInfo(int what, int extra) throws RemoteException {

        }

        @Override
        public void onMediaPlayerPrepared() throws RemoteException {
        }

        @Override
        public void onMediaPlayerSeekComplete() throws RemoteException {

        }
    };
    private int mCurrentAdapterPosition = -1;

    @Override
    public void initTop() {
        enableTop(false);
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.layout_common_recycleview);
    }

    @Override
    public void initViews() {
        mRecyclerView = findView(R.id.rv_common);
        //设置水平布局
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
//        // 设置item动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//        //设置水平分割线
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST
//                , R.drawable.line_divider_one));
        mRecyclerView.setAdapter(mAdapter = new MyRecordAdapter(mContext, null));
    }

    @Override
    public void initDatas() {
        mHandler = new MsgHandler(this);

    }

    @Override
    public void initListeners() {
        mAdapter.setOnStartPlayBackListener(this);//点击播放的时候
        mAdapter.setOnItemClickListener(this);//点击条目的时候
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        new AsyncTask<Void, Void, List>() {

            @Override
            protected List<RecordModel> doInBackground(Void... params) {
                return getRecordData();
            }

            @Override
            protected void onPostExecute(List list) {
                super.onPostExecute(list);
                mAdapter.update(list);
            }
        }.execute();
    }

    /**
     * 从数据库获取录音信息
     */
    private List<RecordModel> getRecordData() {
        RecordDao dao = new RecordDao(mContext);
        List<RecordModel> dramas = new ArrayList<>();
        if (XYJApplication.getUserInfo() != null) {
            dramas = dao.getDramasByUser(XYJApplication.getUserInfo().getUserId());
        }
        return dramas;
    }

    // 开始播放新的文件   暂停/播放旧的音频文件
    protected void startPlayback(String filePath) {
        if (mService == null || !FileUtils.isFileExists(filePath)) {
            return;
        }
        //保存当前播放的音频的url
//        this.mCurrentPlayFilePath = filePath;
        try {
            if (TextUtils.equals(mService.getPath(), filePath) && !isStop) {
                pausePlayback();
                return;
            }
            isStop = false;//重置
            isPause = false;
            mService.stop();
            if (AppConstants.CURRENT_PLAY_STATE == EPlayControlType.PLAY) {//后台在播放的 状态改为暂停
                AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PAUSE;
                EventBusUtil.postEvent(new AnimationEvent(false));//左上角动画 启动
            }
            mService.openFile(filePath);
            mService.play();
            mDuration = mService.duration();
            long next = startRefreshProgressHint();
            sendNextRefreshMessage(next);
        } catch (RemoteException e) {
            e.printStackTrace();
            Log.d("MediaPlaybackActivity", "couldn't start playback: " + e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 暂停/播放
    protected void pausePlayback() {
        try {
            if (mService != null) {
                if (mService.isPlaying()) {
                    mService.pause();
                    isPause = true;
                } else {
                    mService.play();
                    isPause = false;
                    long next = startRefreshProgressHint();
                    sendNextRefreshMessage(next);
                }
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束播放
     */
    private void stopPlayBack() {
        try {
            if (mService != null && mService.isPlaying()) {
                mService.stop();
                mAdapter.setPlayStatus(mPlayStatus, MyRecordAdapter.PlayStatus.PAUSE);
                mTvCurrentTime.setText("0:00");
                mSeekBar.setProgress(0);
                isPause = true;
                isStop = true;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示播放区域
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/18 14:47
     */
    public void showPlayView(MyRecordAdapter.RecordViewHolder viewHolder) {
        viewHolder.mLlPlayArea.setVisibility(View.VISIBLE);
        viewHolder.mVUnderline.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏播放区域
     *
     * @param viewHolder
     */
    public void dismissPlayView(MyRecordAdapter.RecordViewHolder viewHolder) {
        viewHolder.mLlPlayArea.setVisibility(View.GONE);
        viewHolder.mVUnderline.setVisibility(View.GONE);
    }

    private long startRefreshProgressHint() {
        if (mService == null) {
            return 500;
        }
        try {
            int width = 0;
//            mTvTotalTime = getTotalTimeTextView(mCurrentAdapterPosition);
            mTvCurrentTime = getCurrentTimeTextView(mCurrentAdapterPosition);
            mSeekBar = getSeekBar(mCurrentAdapterPosition);
            mPlayStatus = getPlayImgView(mCurrentAdapterPosition);
            long position = mService.position();
            if (position >= 0 && mDuration > 0) {
                if (mTvCurrentTime != null) {
                    mTvCurrentTime.setText(MusicUtils.makeTimeString(mContext, position / 1000));
                }
                int progress = (int) (1000.0f * position / mDuration);
                if (mSeekBar != null) {
                    mSeekBar.setProgress(progress);
                    width = mSeekBar.getWidth();
                }
            }
            long remaining = 1000 - (position % 1000);
            if (width == 0) width = 320;
            long smoothrefreshtime = mDuration / width;
            if (smoothrefreshtime > remaining) return remaining;
            if (smoothrefreshtime < 20) return 20;
            return smoothrefreshtime;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return 500;
    }

    // 发送进度刷新消息
    private void sendNextRefreshMessage(long delay) {
        if (!isPause && mHandler != null) {
            Message msg = mHandler.obtainMessage(MSG_REFRESH_PROGRESS_POS);
            mHandler.removeMessages(MSG_REFRESH_PROGRESS_POS);
            mHandler.sendMessageDelayed(msg, delay);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        // 绑定媒体播放service
        mToken = MusicUtils.bindToService(getActivity(), mServiceConnection);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        try {
            if (mService.isPlaying() && AppConstants.CURRENT_PLAY_STATE != EPlayControlType.PLAY) {//在播放
                Log.d("debug", "进来了？？？");
                stopPlayBack();//结束播放
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        MusicUtils.unbindFromService(mToken);//解绑
    }

    @Override
    public void onStartPlayBack(String filePath) {
        startPlayback(filePath);
    }

    @Override
    public void onPausePlayBack() {
        pausePlayback();
    }

    private MyRecordAdapter.RecordViewHolder getRecordViewHolder(int adapterPosition) {
        RecyclerView.ViewHolder viewHolder = mRecyclerView.findViewHolderForAdapterPosition(adapterPosition);
        if (viewHolder instanceof MyRecordAdapter.RecordViewHolder) {
            return (MyRecordAdapter.RecordViewHolder) viewHolder;
        }
        return null;
    }

    /**
     * 获取当前播放的进度条的 当前播放时间
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/18 10:46
     */
    private MyTextView getCurrentTimeTextView(int adapterPosition) {
        MyRecordAdapter.RecordViewHolder viewHolder = getRecordViewHolder(adapterPosition);
        if (viewHolder != null) {
            return viewHolder.mTvCurrentPlayTime;
        }
        return null;
    }

    /**
     * 获取当前播放的进度条的 总的播放时间
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/18 10:46
     */
    private MyTextView getTotalTimeTextView(int adapterPosition) {
        MyRecordAdapter.RecordViewHolder viewHolder = getRecordViewHolder(adapterPosition);
        if (viewHolder != null) {
            return viewHolder.mTvTotalPlayTime;
        }
        return null;
    }

    /**
     * 获取当前播放的进度条的 进度条
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/18 10:46
     */
    private SeekBar getSeekBar(int adapterPosition) {
        MyRecordAdapter.RecordViewHolder viewHolder = getRecordViewHolder(adapterPosition);
        if (viewHolder != null) {
            return viewHolder.mSeekBar;
        }
        return null;
    }

    private ImageView getPlayImgView(int adapterPosition) {
        MyRecordAdapter.RecordViewHolder viewHolder = getRecordViewHolder(adapterPosition);
        if (viewHolder != null) {
            return viewHolder.mIvPlay;
        }
        return null;
    }

    @Override
    public void onItemClick(int adapterPosition) {//点击 条目回调
        if (mCurrentAdapterPosition != -1
                && mCurrentAdapterPosition != adapterPosition) {//不是第一次点击 && 点击不同的
            //隐藏刚才打开的
            dismissPlayView(getRecordViewHolder(mCurrentAdapterPosition));
            stopPlayBack();
        }
        showPlayView(getRecordViewHolder(adapterPosition));
        mCurrentAdapterPosition = adapterPosition;
    }

    protected static class MsgHandler extends Handler {
        protected WeakReference<MyRecordFragment> reference;

        public MsgHandler(MyRecordFragment fragment) {
            reference = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            MyRecordFragment fragment = reference.get();
            if (fragment == null) {
                return;
            }
            switch (msg.what) {
                case MSG_REFRESH_PROGRESS_POS:
                    long next = fragment.startRefreshProgressHint();
                    fragment.sendNextRefreshMessage(next);
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
